<template>
  <div class="workflow-designer-page">
    <div class="header">
      <h2>工作流设计器</h2>
      <div class="header-actions">
        <el-button @click="goBack">返回列表</el-button>
        <el-button type="primary" @click="saveWorkflow">保存工作流</el-button>
        <el-button @click="loadWorkflow">加载工作流</el-button>
        <el-button @click="clearCanvas">清空画布</el-button>
      </div>
    </div>
    
    <div class="designer-container">
      <!-- 左侧节点类型面板 -->
      <WorkflowNodePanel />
      
      <!-- 中间画布区 -->
      <div class="canvas-container">
        <div class="canvas-toolbar">
          <el-button size="small" @click="startWorkflow" :disabled="isRunning">开始流程</el-button>
          <el-button size="small" @click="completeNode" :disabled="!isRunning || !activeNodeId">完成节点</el-button>
          <el-button size="small" @click="stopWorkflow" :disabled="!isRunning">停止流程</el-button>
          <el-button size="small" @click="autoLayout">自动布局</el-button>
          <el-button size="small" @click="testConditions" :disabled="!activeNodeId">测试条件</el-button>
        </div>
        
        <WorkflowCanvas
          :nodes="nodes"
          :connections="connections"
          @update:nodes="updateNodes"
          @update:connections="updateConnections"
          @selectNode="selectNode"
        />
        
        <!-- 流程状态显示 -->
        <div class="workflow-status">
          <div>状态: {{ isRunning ? '运行中' : '未开始' }}</div>
          <div v-if="activeNodeId">当前节点: {{ getActiveNodeName() }}</div>
          <div>已完成: {{ completedNodeIds.length }} / {{ nodes.length }}</div>
        </div>
      </div>
      
      <!-- 右侧属性编辑面板 -->
      <WorkflowNodeProperty 
        :node="selectedNode" 
        @update:node="updateNodeProperties"
        @delete:node="deleteSelectedNode"
      />
    </div>
    
    <!-- 保存对话框 -->
    <el-dialog v-model="showSaveDialog" title="保存工作流" width="400px">
      <el-form>
        <el-form-item label="工作流名称">
          <el-input v-model="workflowName" placeholder="请输入工作流名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSaveDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSave">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 加载对话框 -->
    <el-dialog v-model="showLoadDialog" title="加载工作流" width="500px">
      <div v-if="savedWorkflows.length === 0" style="text-align: center; color: #999; padding: 40px;">
        暂无保存的工作流
      </div>
      <div v-else>
        <div
          v-for="workflow in savedWorkflows"
          :key="workflow.id"
          class="workflow-item"
          @click="loadWorkflowData(workflow)"
        >
          <div class="workflow-name">{{ workflow.name }}</div>
          <div class="workflow-info">
            节点: {{ workflow.nodes?.length || 0 }} | 
            连接线: {{ workflow.connections?.length || 0 }} | 
            创建: {{ formatDate(workflow.createdAt) }}
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showLoadDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import WorkflowNodePanel from '@/components/WorkflowNodePanel.vue'
import WorkflowCanvas from '@/components/WorkflowCanvas.vue'
import WorkflowNodeProperty from '@/components/WorkflowNodeProperty.vue'

const router = useRouter()
const route = useRoute()

// 状态管理
const nodes = ref<any[]>([])
const connections = ref<any[]>([])
const selectedNode = ref<any>(null)
const isRunning = ref(false)
const activeNodeId = ref<any>(null)
const completedNodeIds = ref<any[]>([])

// 对话框状态
const showSaveDialog = ref(false)
const showLoadDialog = ref(false)
const workflowName = ref('')
const savedWorkflows = ref<any[]>([])

// 本地存储
const STORAGE_KEY = 'workflow_list'

function getWorkflows() {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
  } catch {
    return []
  }
}

function setWorkflows(list: any[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(list))
}

// 导航
function goBack() {
  router.push('/settings/workflow')
}

// 节点管理
function updateNodes(newNodes: any[]) {
  nodes.value = newNodes
}

function updateConnections(newConnections: any[]) {
  connections.value = newConnections
}

function selectNode(node: any) {
  selectedNode.value = node
}

function updateNodeProperties(updatedNode: any) {
  // 更新节点属性
  const index = nodes.value.findIndex(n => n.id === updatedNode.id)
  if (index !== -1) {
    nodes.value[index] = { ...nodes.value[index], ...updatedNode }
  }
}

function deleteSelectedNode(nodeId: string | number) {
  // 删除选中的节点
  nodes.value = nodes.value.filter(n => n.id !== nodeId)
  connections.value = connections.value.filter(c => c.from !== nodeId && c.to !== nodeId)
  selectedNode.value = null
}

// 流程控制
function startWorkflow() {
  if (nodes.value.length === 0) {
    ElMessage.warning('请先添加节点到画布')
    return
  }
  
  // 找到起始节点（没有入边的节点）
  const startNodes = nodes.value.filter(node => 
    !connections.value.some(conn => conn.to === node.id)
  )
  
  if (startNodes.length === 0) {
    ElMessage.warning('请先连接节点形成流程')
    return
  }
  
  if (startNodes.length > 1) {
    ElMessage.warning('流程只能有一个起始节点')
    return
  }
  
  isRunning.value = true
  activeNodeId.value = startNodes[0].id
  completedNodeIds.value = []
  ElMessage.success('流程已开始')
}

function completeNode() {
  if (!activeNodeId.value) return
  
  const activeNode = nodes.value.find(n => n.id === activeNodeId.value)
  if (!activeNode) return
  
  // 处理节点通知（如果配置了的话）
  if (activeNode.notifyTargets && activeNode.notifyTargets.length > 0) {
    const message = activeNode.remindTemplate || `${activeNode.name}节点执行完成`
    const targets = activeNode.notifyTargets.join('、')
    const methods = activeNode.notifyMethods?.join('、') || '系统消息'
    ElMessage.success(`📢 通知${targets}：${message} (通过${methods})`)
  }
  
  // 处理系统节点的特殊逻辑
  if (activeNode.type === '系统') {
    if (activeNode.name === '数据验证') {
      ElMessage.success(`🔍 数据验证完成：${activeNode.description || '验证通过'}`)
    } else if (activeNode.name === '日志记录') {
      ElMessage.success(`📝 日志记录：${activeNode.description || '操作已记录'}`)
    }
  }
  
  // 标记当前节点为已完成
  completedNodeIds.value.push(activeNodeId.value)
  
  // 找到下一个节点
  const nextConnection = connections.value.find(conn => conn.from === activeNodeId.value)
  
  if (nextConnection) {
    // 移动到下一个节点
    activeNodeId.value = nextConnection.to
  } else {
    // 流程结束
    isRunning.value = false
    activeNodeId.value = null
    ElMessage.success('流程执行完成！')
  }
}

function stopWorkflow() {
  isRunning.value = false
  activeNodeId.value = null
  completedNodeIds.value = []
  ElMessage.info('流程已停止')
}

function getActiveNodeName() {
  const node = nodes.value.find(n => n.id === activeNodeId.value)
  return node?.name || '未知'
}

// 测试执行条件
function testConditions() {
  if (!activeNodeId.value) return
  
  const activeNode = nodes.value.find(n => n.id === activeNodeId.value)
  if (!activeNode) return
  
  if (!activeNode.condition) {
    ElMessage.info('当前节点没有设置执行条件')
    return
  }
  
  // 模拟测试数据
  const testData = {
    '订单金额': 1500,
    '用户等级': 4,
    '库存数量': 10,
    '订单状态': '已确认',
    '用户类型': 'VIP',
    '工作日': true,
    '订单号': 'ORD2024001',
    '用户ID': 12345,
    '商品分类': '电子产品',
    '当前时间': new Date().toISOString(),
    '系统状态': '正常'
  }
  
  try {
    // 简单的条件评估（实际项目中应该使用更安全的表达式解析器）
    const condition = activeNode.condition
    let result = false
    
    // 替换变量
    let evaluatedCondition = condition
    Object.entries(testData).forEach(([key, value]) => {
      const regex = new RegExp(`{{${key}}}`, 'g')
      if (typeof value === 'string') {
        evaluatedCondition = evaluatedCondition.replace(regex, `"${value}"`)
      } else {
        evaluatedCondition = evaluatedCondition.replace(regex, value.toString())
      }
    })
    
    // 简单的条件检查（仅用于演示）
    if (condition.includes('订单金额 > 1000') && testData['订单金额'] > 1000) result = true
    if (condition.includes('用户等级 >= 3') && testData['用户等级'] >= 3) result = true
    if (condition.includes('库存数量 > 0') && testData['库存数量'] > 0) result = true
    if (condition.includes('订单状态 === "已确认"') && testData['订单状态'] === '已确认') result = true
    if (condition.includes('用户类型 === "VIP"') && testData['用户类型'] === 'VIP') result = true
    if (condition.includes('工作日 === true') && testData['工作日'] === true) result = true
    
    // 如果没有匹配到预设条件，默认通过
    if (!condition.includes('>') && !condition.includes('>=') && !condition.includes('===')) {
      result = true
    }
    
    if (result) {
      ElMessage.success(`✅ 执行条件满足：${condition}`)
    } else {
      ElMessage.warning(`❌ 执行条件不满足：${condition}`)
    }
    
    // 显示测试数据
    ElMessage.info(`测试数据：${JSON.stringify(testData, null, 2)}`)
    
  } catch (error) {
    ElMessage.error(`条件评估出错：${error}`)
  }
}

// 布局
function autoLayout() {
  if (nodes.value.length === 0) {
    ElMessage.warning('画布为空')
    return
  }
  
  // 简单垂直布局
  const newNodes = nodes.value.map((node, index) => ({
    ...node,
    x: 100,
    y: 60 + index * 120
  }))
  
  nodes.value = newNodes
  ElMessage.success('布局已整理')
}

// 保存/加载
function saveWorkflow() {
  if (nodes.value.length === 0) {
    ElMessage.warning('请先添加节点到画布')
    return
  }
  showSaveDialog.value = true
}

async function confirmSave() {
  if (!workflowName.value.trim()) {
    ElMessage.warning('请输入工作流名称')
    return
  }
  
  const workflowData = {
    id: route.params.id || Date.now(),
    name: workflowName.value.trim(),
    nodes: nodes.value,
    connections: connections.value,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }
  
  let list = getWorkflows()
  if (route.params.id) {
    list = list.map(w => w.id === route.params.id ? workflowData : w)
  } else {
    list = [...list, workflowData]
  }
  
  setWorkflows(list)
  savedWorkflows.value = list
  showSaveDialog.value = false
  ElMessage.success(`工作流"${workflowName.value}"已保存！`)
}

function loadWorkflow() {
  savedWorkflows.value = getWorkflows()
  showLoadDialog.value = true
}

function loadWorkflowData(workflow: any) {
  if (nodes.value.length > 0) {
    ElMessageBox.confirm('当前画布已有内容，是否要清空并加载选中的工作流？', '确认加载', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      loadWorkflowToCanvas(workflow)
    }).catch(() => {
      // 用户取消
    })
  } else {
    loadWorkflowToCanvas(workflow)
  }
}

function loadWorkflowToCanvas(workflow: any) {
  nodes.value = workflow.nodes || []
  connections.value = workflow.connections || []
  selectedNode.value = null
  activeNodeId.value = null
  completedNodeIds.value = []
  isRunning.value = false
  showLoadDialog.value = false
  ElMessage.success(`已加载工作流"${workflow.name}"！`)
}

function clearCanvas() {
  if (nodes.value.length === 0) {
    ElMessage.warning('画布已经是空的')
    return
  }
  
  ElMessageBox.confirm('确定要清空画布吗？此操作不可撤销。', '确认清空', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    nodes.value = []
    connections.value = []
    selectedNode.value = null
    activeNodeId.value = null
    completedNodeIds.value = []
    isRunning.value = false
    ElMessage.success('画布已清空！')
  }).catch(() => {
    // 用户取消
  })
}

function formatDate(dateString: string) {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString()
}

// 初始化
onMounted(() => {
  // 如果是编辑模式，加载现有工作流
  if (route.params.id) {
    const list = getWorkflows()
    const workflow = list.find(w => w.id === route.params.id)
    if (workflow) {
      nodes.value = workflow.nodes || []
      connections.value = workflow.connections || []
      workflowName.value = workflow.name
    }
  }
})
</script>

<style scoped>
.workflow-designer-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.designer-container {
  display: flex;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f3;
  overflow: hidden;
  min-height: 600px;
}

.canvas-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  min-height: 800px;
  overflow: hidden;
}

.canvas-toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.workflow-status {
  margin-top: 16px;
  padding: 12px;
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  font-size: 14px;
  color: #1890ff;
}

.workflow-item {
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.workflow-item:hover {
  background: #f5f5f5;
  border-color: #1890ff;
}

.workflow-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.workflow-info {
  font-size: 12px;
  color: #666;
}
</style> 